package com.ruoyi.system.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysDictData;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;

/**
 * 数据字典信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/dict/data")
public class SysDictDataController extends BaseController
{
    @Autowired
    private ISysDictDataService dictDataService;
    
    @Autowired
    private ISysDictTypeService dictTypeService;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String DISTLIST = "distlist";

    @RequiresPermissions("system:dict:list")
    @GetMapping("/list")
    public TableDataInfo list(SysDictData dictData)
    {
        startPage();
        String dictType = dictData.getDictType();
        String dictLabel = dictData.getDictLabel();
        String status = dictData.getStatus();
        dictData.setDictLabel("");
        if(!redisTemplate.hasKey(getKey(dictType))){
            //同步锁，防止缓存击穿
            synchronized (this){
                if(!redisTemplate.hasKey(getKey(dictType))){
                    List<SysDictData> list = dictDataService.selectDictDataList(dictData);
                    List<SysDictData> collect = list;
                    collect = filterlist(collect,dictLabel,status);
//                    for(SysDictData dictData1 : list){
//                        redisTemplate.opsForHash().put(dictType+"distlist",dictData1.getDictCode(),dictData1);
//                    }
                    //redisTemplate.opsForValue().set(dictType+"distlist",list,140, TimeUnit.MINUTES);
                    reflash(getKey(dictType),list);
                    return getDataTable(collect);
                }
            }
        }

       //List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        Object o = redisTemplate.opsForValue().get(getKey(dictType));
        List<SysDictData> list = null;
        if(Objects.nonNull(o)){
            list= (List<SysDictData>)o;
        }
        List<SysDictData> collect = list;
        collect = filterlist(collect,dictLabel,status);
        return getDataTable(collect);
    }

    //过滤
    private List<SysDictData> filterlist(List<SysDictData> collect,String dictLabel,String status){
        if(Objects.nonNull(collect)){
            if(StringUtils.isNotEmpty(dictLabel) && StringUtils.isNotNull(dictLabel)){
                collect = collect.stream().filter(sysDictData -> sysDictData.getDictLabel().contains(dictLabel)).collect(Collectors.toList());
            }
            if(StringUtils.isNotEmpty(status) && StringUtils.isNotNull(status)){
                collect = collect.stream().filter(sysDictData -> sysDictData.getStatus().contains(status)).collect(Collectors.toList());
            }
        }
        return collect;
    }

    //获得KEY
    private String getKey(String dictType){
        return dictType+DISTLIST;
    }

    //刷新缓存
    private void reflash(String key,List<SysDictData> list){
        if(redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
        }
        redisTemplate.opsForValue().set(key,list,140, TimeUnit.MINUTES);
    }

    //数据获取
    private List<SysDictData> getDataList(String type){
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(type);
        return dictDataService.selectDictDataList(sysDictData);
    }

    @Log(title = "字典数据", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:dict:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysDictData dictData)
    {
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        ExcelUtil<SysDictData> util = new ExcelUtil<SysDictData>(SysDictData.class);
        util.exportExcel(response, list, "字典数据");
    }

    /**
     * 查询字典数据详细
     */
    @RequiresPermissions("system:dict:query")
    @GetMapping(value = "/{dictCode}")
    public AjaxResult getInfo(@PathVariable Long dictCode)
    {
        return success(dictDataService.selectDictDataById(dictCode));
    }

    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/type/{dictType}")
    public AjaxResult dictType(@PathVariable String dictType)
    {
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data))
        {
            data = new ArrayList<SysDictData>();
        }
        return success(data);
    }

    /**
     * 新增字典类型
     */
    @RequiresPermissions("system:dict:add")
    @Log(title = "字典数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDictData dict)
    {
        dict.setCreateBy(SecurityUtils.getUsername());
        int i = dictDataService.insertDictData(dict);
        if(i>0){
            List<SysDictData> dataList = getDataList(dict.getDictType());
            reflash(getKey(dict.getDictType()),dataList);
        }
        return toAjax(i);
    }

    /**
     * 修改保存字典类型
     */
    @RequiresPermissions("system:dict:edit")
    @Log(title = "字典数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDictData dict)
    {
        dict.setUpdateBy(SecurityUtils.getUsername());
        int i = dictDataService.updateDictData(dict);
        if(i>0){
            List<SysDictData> dataList = getDataList(dict.getDictType());
            reflash(getKey(dict.getDictType()),dataList);
        }
        return toAjax(i);
    }

    /**
     * 删除字典类型
     */
    @RequiresPermissions("system:dict:remove")
    @Log(title = "字典类型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dictCodes}")
    public AjaxResult remove(@PathVariable Long[] dictCodes)
    {
        SysDictData sysDictData = dictDataService.selectDictDataById(dictCodes[0]);
        dictDataService.deleteDictDataByIds(dictCodes);
        reflash(getKey(sysDictData.getDictType()),getDataList(sysDictData.getDictType()));
        return success();
    }
}
